import React from 'react';
import {
    Card, Button, Row, Col, Radio,
    Form, Checkbox, Tabs, message, Modal,
    Input, InputNumber, Table, Space, Alert
} from 'antd';
import {
    PlusOutlined,
    ExclamationCircleOutlined,
} from '@ant-design/icons';
import { connect } from 'umi';
import request from '@/utils/request';
import { WhseSelect, OpMasterSelect } from '@/components/FormItemSelect';

const apiURL = "/api/services/app/Resource/";
const { TabPane } = Tabs;
const { confirm } = Modal;
const currentControl = "Resource";
class ViewPage extends React.Component<any, any> {
    constructor(props: Readonly<{}>) {
        super(props);
        this.state = {
            loading: false,
            visible: false,
            data: { id: 0 },
            dataSource: [],
            defTab: '2'
        }
    }
    componentDidMount() {
        this.fetchData();
    }
    formRef: any = React.createRef();
    onFinish = (values: any) => {
        const { ResourceGrp } = this.props
        if (!ResourceGrp.resourceGrpID) {
            message.error("请先选择资源组")
            return;
        }
        var model = values.Resource
        this.setState({ loading: true });
        var act = "Modify";
        if (model.id == 0 || !model.id) {
            act = "New";
        }
        model.resourceGrpID = ResourceGrp.resourceGrpID
        model.inspPlanPartNum = "0"
        model.url = "0"
        model.calendarID = "0"
        model.burdenType = "0"
        model.assetNum = "0"
        model.linkedPart = "0"
        model.opStdID = "0"
        request(apiURL + act, {
            method: 'POST',
            data: model
        }).then((response) => {
            if (response) {
                if (response.success) {
                    if (response.result.success) {
                        message.success('保存成功！');
                        this.setState({ data: response.result.data })
                        this.fetchData()
                    }
                    else {
                        message.error(response.result.message);
                    }
                }
                else {
                    message.error(response.error.message);
                }
                this.setState({ loading: false });
            }
        });
    }
    resetForm = () => {
        this.formRef.current.resetFields()
        this.setState({ defTab: '1', data: { id: 0 } })
    }
    getData = (value: any) => {
        if (value) {
            request(apiURL + 'GetByCode', {
                method: 'GET',
                params: { code: value }
            }).then((response: any) => {
                if (response.success) {
                    if (response.result.success) {
                        this.formRef.current.setFieldsValue({ Resource: response.result.data });
                        this.setState({ data: response.result.data })
                    }
                    else {
                        message.warning(response.result.message);
                    }
                }
            });
        }
    }
    setData = (item: any) => {
        if (item) {
            this.setState({ defTab: '1' })
            this.getData(item.resourceID)
        }
    }
    fetchData = () => {
        request(apiURL + 'GetList', {
            method: 'GET'
        }).then((response: any) => {
            if (response && response.success) {
                var dataSource = response.result.items
                this.setState({ dataSource })
            }
        });
    }
    tabSwitch = (key: any) => {
        this.setState({ defTab: key });
    }
    delObj = () => {
        const { data } = this.state
        let _this = this
        confirm({
            title: '警告',
            icon: <ExclamationCircleOutlined />,
            content: '删除后将不可恢复，确定删除？',
            onOk() {
                _this.props.dispatch({
                    type: 'Abp/delete',
                    payload: { id: data.id },
                    control: currentControl
                }).then(() => {
                    _this.formRef.current.resetFields()
                    _this.fetchData()
                    _this.setState({ data: { id: 0 } })
                })
            },
        });
    }
    render() {
        const { ResourceGrp } = this.props
        const { defTab, data } = this.state
        const layout = {
            labelCol: { span: 5 },
            wrapperCol: { span: 19 },
        };
        const columns = [
            {
                title: '资源代码',
                dataIndex: 'resourceID',
                key: 'resourceID',
            },
            {
                title: '资源描述',
                dataIndex: 'description',
                key: 'description',
            },
            {
                title: '无效',
                dataIndex: 'inactive',
                key: 'inactive',
                render: (text: boolean) => (
                    <Checkbox checked={text} />
                )
            },
            {
                title: '并发能力',
                dataIndex: 'concurrentCapacity',
                key: 'concurrentCapacity',
            },
            {
                title: '默认工序',
                dataIndex: 'opCode',
                key: 'opCode',
            },
            {
                title: '日产量',
                dataIndex: 'dailyProdQty',
                key: 'dailyProdQty',
            },

        ];
        const dataSource = this.state.dataSource.filter((o: any) => o.resourceGrpID == ResourceGrp.resourceGrpID)
        return (
            <Form {...layout} ref={this.formRef} onFinish={this.onFinish} >
                <Card title={ResourceGrp?.description ? ResourceGrp?.description : "" + "资源"} extra={[<Space key="s1">
                    <Button type="primary" icon={<PlusOutlined />} onClick={this.resetForm}>新增</Button>
                    <Button type="primary" htmlType="submit" loading={this.state.loading}>保存</Button>
                    <Button danger onClick={this.delObj} disabled={data.id === 0}>删除</Button>
                </Space>]}>
                    <Tabs defaultActiveKey={defTab} activeKey={defTab} onChange={this.tabSwitch}>
                        <TabPane tab="明细" key="1">
                            <Row>
                                <Col span={12}>
                                    <Form.Item label="ID" name={['Resource', 'id']} hidden>
                                        <Input />
                                    </Form.Item>
                                    <Form.Item
                                        label="资源代码"
                                        name={['Resource', 'resourceID']}
                                        rules={[{ required: true }]}>
                                        <Input onBlur={(e: any) => this.getData(e.target.value)} style={{ width: 200 }} />
                                    </Form.Item>
                                    <Form.Item label="描述" name={['Resource', 'description']}>
                                        <Input />
                                    </Form.Item>
                                    <Form.Item label="入料仓库" style={{ marginBottom: 0 }}>
                                        <Input.Group compact>
                                            <WhseSelect width={200} required={true} showSearch={false} name={['Resource', 'inputWhse']} placeholder="入料仓库" />
                                            <Form.Item name={['Resource', 'inputBinNum']} rules={[{ required: true, message: "入料库位必填" }]}>
                                                <Input style={{ width: 100 }} placeholder="库位" />
                                            </Form.Item>
                                        </Input.Group>
                                    </Form.Item>
                                    <Form.Item label="出料仓库" style={{ marginBottom: 0 }}>
                                        <Input.Group compact>
                                            <WhseSelect width={200} required={true} showSearch={false} name={['Resource', 'outputWhse']} placeholder="出料仓库" />
                                            <Form.Item name={['Resource', 'outputBinNum']} rules={[{ required: true, message: "出料库位必填" }]}>
                                                <Input style={{ width: 100 }} placeholder="库位" />
                                            </Form.Item>
                                        </Input.Group>
                                    </Form.Item>
                                    <Form.Item label="反冲仓库" style={{ marginBottom: 0 }}>
                                        <Input.Group compact>
                                            <WhseSelect width={200} required={true} showSearch={false} name={['Resource', 'backflushWhse']} placeholder="反冲仓库" />
                                            <Form.Item name={['Resource', 'backflushBinNum']} rules={[{ required: true, message: "反冲库位必填" }]}>
                                                <Input style={{ width: 100 }} placeholder="库位" />
                                            </Form.Item>
                                        </Input.Group>
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item
                                        wrapperCol={{ offset: 5 }}
                                        name={['Resource', 'inactive']}
                                        valuePropName="checked">
                                        <Checkbox>无效</Checkbox>
                                    </Form.Item>
                                    <Form.Item
                                        label='资源类型'
                                        rules={[{ required: true }]}
                                        name={['Resource', 'resourceType']}>
                                        <Radio.Group>
                                            <Radio value='P'>人</Radio>
                                            <Radio value='M'>机器</Radio>
                                        </Radio.Group>
                                    </Form.Item>
                                    <OpMasterSelect width={200} required={true} showSearch={false} name={['Resource', 'opCode']} label="默认工序" />
                                    <Form.Item
                                        label="排队时间"
                                        name={['Resource', 'queHours']}>
                                        <InputNumber min={0} />
                                    </Form.Item>
                                    <Form.Item
                                        label="日生产能力"
                                        name={['Resource', 'dailyProdQty']}
                                        rules={[{ required: true }]}>
                                        <InputNumber min={0} />
                                    </Form.Item>
                                </Col>
                            </Row>

                        </TabPane>
                        <TabPane tab="列表" key="2">
                            <Table
                                rowKey="id"
                                size="small"
                                columns={columns}
                                dataSource={dataSource}
                                onRow={record => {
                                    return {
                                        onDoubleClick: event => { this.setData(record) },
                                    };
                                }}
                                footer={() => <Alert
                                    message="双击任意行进行编辑"
                                    type="warning"
                                    showIcon
                                    closable
                                />} />

                        </TabPane>
                    </Tabs>
                </Card>
            </Form>
        )
    }
}
export default connect(({ Abp }: API.IConnectState) => ({
    response: Abp.response,
    currentUser: Abp.currentUser,
}))(ViewPage);